package processor

import (
	"encoding/json"
	"fmt"
	"net"

	"github.com/clebeg/gochat/protocol"
	"github.com/clebeg/gochat/server/manager"
	"github.com/clebeg/gochat/utils"
)

// 服务端聊天处理器
type ChatProcessor struct {
	Conn net.Conn
}

func groupChat(jsonBytes []byte, sendUsername int) {
	for un, ui := range manager.UserMgr.OnlineUsers {
		if un == sendUsername {
			continue
		}
		transfer := utils.Transfer{
			Conn: ui.Conn,
		}
		err := transfer.SendMsg(jsonBytes, protocol.ChatMsgType)

		if err != nil {
			fmt.Printf("transfer.SendMsg(jsonBytes, protocol.ChatMsgType) err, err msg=%v\n", err)
		}
	}
}

func oneChat(jsonBytes []byte, receiveUsername int) {
	for un, ui := range manager.UserMgr.OnlineUsers {
		if un == receiveUsername {
			transfer := utils.Transfer{
				Conn: ui.Conn,
			}
			err := transfer.SendMsg(jsonBytes, protocol.ChatMsgType)

			if err != nil {
				fmt.Printf("transfer.SendMsg(jsonBytes, protocol.ChatMsgType) err, err msg=%v\n", err)
			}
		}
	}
}

// 处理用户登录请求
func (u *ChatProcessor) ChatProcess(chatData string, sendUsername int, receiveUsername int) {
	respMsg := protocol.ChatMsgResp{
		ChatMsgReq: protocol.ChatMsgReq{
			SendUserName:    sendUsername,
			ChatData:        chatData,
			ReceiveUsername: receiveUsername,
		},
	}

	jsonBytes, err := json.Marshal(respMsg)

	if err != nil {
		fmt.Printf("notify login json.Marshal(respMsg) err, err msg=%v\n", err)
	}

	if receiveUsername == 0 {
		groupChat(jsonBytes, sendUsername)
	} else {
		oneChat(jsonBytes, receiveUsername)
	}
}
